package com.hucheng.goods.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.hucheng.common.page.CommonPager;
import com.hucheng.common.page.PageParameter;
import com.hucheng.goods.dto.CartDTO;
import com.hucheng.goods.entity.CartDO;
import com.hucheng.goods.mapper.CartMapper;
import com.hucheng.goods.query.CartQuery;
import com.hucheng.goods.service.CartService;
import com.hucheng.goods.vo.CartVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.stream.Collectors;

/**
 * @Author: 凉白开不加冰
 * @Version: 0.0.1V
 * @Date: 2019-07-22
 * @Description: 类描述
 **/
@Component
@Service(interfaceClass = CartService.class, retries = -1, timeout = 5000)
public class CartServiceImpl implements CartService {

    @Autowired
    private CartMapper cartMapper;

    @Override
    public void addCart(CartDTO cartDTO) {
        CartDO cartDO = cartMapper.get(cartDTO.getUserId(), cartDTO.getGoodsId());
        if (cartDO != null) {
            cartMapper.update(CartDO.buildCartDO(cartDTO));
        } else {
            cartDTO.setIsDel(0);
            cartMapper.insert(CartDO.buildCartDO(cartDTO));
        }
    }

    @Override
    public CommonPager<CartVO> cartLists(CartQuery cartQuery) {
        return new CommonPager<>(new PageParameter(cartQuery.getPageParameter().getCurrentPage(),
                cartQuery.getPageParameter().getPageSize(), cartMapper.count(cartQuery)),
                cartMapper.list(cartQuery).stream().map(CartVO::buildCartVO).collect(Collectors.toList()));
    }

    @Override
    public CommonPager<CartVO> delCart(Integer cartId, Integer userId) {

        cartMapper.del(userId, cartId);

        PageParameter pageParameter = new PageParameter();

        CartQuery cartQuery = new CartQuery();
        cartQuery.setUserId(userId);
        cartQuery.setPageParameter(pageParameter);
        return new CommonPager<>(new PageParameter(cartQuery.getPageParameter().getCurrentPage(),
                cartQuery.getPageParameter().getPageSize(), cartMapper.count(cartQuery)),
                cartMapper.list(cartQuery).stream().map(CartVO::buildCartVO).collect(Collectors.toList()));
    }
}
